// Copyright NaChuanSoftware Author(https://github.com/LiuShuKu). All Rights Reserved.

// Copyright (c)  2023 LiuShuKu
// Project Name :   balance
// Author       :   liushuku@yeah.net

// Package tron .
package tron

import (
	"context"
	"github.com/btcsuite/btcutil/base58"
	"github.com/ethereum/go-ethereum/crypto"
	addr "github.com/fbsobreira/gotron-sdk/pkg/address"
	"github.com/gogf/gf/v2/errors/gerror"
	"regexp"
)

type tron struct {
}

var Tron = &tron{}

// 转账类型
const (
	typeUsdt = 1
	typeTrx  = 0
)

// Usdt 转账
const (
	feeLimit = 100000000                            // 最大限额
	contract = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" // 合约地址
)

const (
	tronUnit = 1000000 // Trc20 精度
)

// CheckTrc20Address 检查trx20 地址
func (t *tron) CheckTrc20Address(ctx context.Context, trc20Address string) (err error) {
	var (
		regexpRes bool
		version   byte
	)
	{
		if regexpRes, err = regexp.MatchString(`^T[a-zA-Z0-9]{33}$`, trc20Address); !regexpRes || err != nil {
			err = gerror.New("钱包地址格式不合法")
			return
		}
	}
	{
		if _, version, err = base58.CheckDecode(trc20Address); err != nil || version != 0x41 {
			err = gerror.New("钱包地址格被篡改")
			return
		}
	}
	return
}

// GetTrc20AddressByPrivateKey 获取Trc20地址根据私钥
func (t *tron) GetTrc20AddressByPrivateKey(ctx context.Context, privateKey string) (trc20Address string, err error) {
	pri, err := crypto.HexToECDSA(privateKey)
	if err != nil {
		err = gerror.New("trc20私钥不合法")
		return
	}
	trc20Address = addr.PubkeyToAddress(pri.PublicKey).String()
	return
}
